package com.wechat.controller;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.wechat.api.BaiduAPI;
import com.wechat.service.UserService;
import com.wechat.service.WechatService;
import com.wechat.util.MyUtil;

@Controller
@RequestMapping("/WechatController")
public class WechatController {
	@Autowired
	private WechatService wechatService;
	@Autowired
	private UserService userService;
	@Autowired
	private BaiduAPI BaiduAPI;
	/**
	 * 校验开发者服务器
	 *@dagewang 
	 *2017年11月22日
	 */
	@RequestMapping("/wechatCheck")
	public @ResponseBody String wechatCheck(String signature, String timestamp, String nonce, String echostr)
			throws Exception {
		MyUtil myUtil = MyUtil.getMyUtil();
		String token = "dagewang";
		List<String> list = new ArrayList<String>();
		list.add(nonce);
		list.add(timestamp);
		list.add(token);
		Collections.sort(list);
		String str = list.get(0) + list.get(1) + list.get(2);
		String sha1 = myUtil.getSha1(str);
		if (sha1.equals(signature)) {
			return echostr;
		}
		return "";
	}
	/**
	 * 推送消息接收
	 *@dagewang 
	 *2017年11月22日
	 */
	@RequestMapping(value = "/push", method = RequestMethod.POST)
	public void push(HttpServletRequest hsr, HttpServletResponse response) throws Exception {
		boolean mySwitch = false;
		MyUtil myUtil = MyUtil.getMyUtil();
		Map<String, String> xmlToMap = myUtil.xmlToMap(hsr);
		String type = xmlToMap.get("MsgType");
		String result = "success";
		switch (type) {
		case "text":
			result = wechatService.textHandle(xmlToMap);
			mySwitch = true;
			break;
		case "event":
			result = userService.save(xmlToMap);
			if (result != null)
				mySwitch = true;
			break;
		case "location":
			result = BaiduAPI.nearbyGet(xmlToMap);
				mySwitch = true;
			break;

		default:
			break;
		}
		if (mySwitch) {
			response.setContentType("text/html;charset=utf-8");
			PrintWriter out = response.getWriter();
			out.println(myUtil.toXMLText(xmlToMap,result));
			out.flush();
			out.close();
		}
	}

}
